package com.guchenbo.example.lock.latch;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch类，可以让一个或多个线程一直等待，直到其他线程完成一组任务之后
 * 这个示例，将演示一个线程在等待，直到其他线程完成一组操作
 * <p/>
 * <p/>
 * Created by CreGu on 2016/6/22.
 */
public class TestCountDownLatch {

    public static final int LATCH_SIZE = 1;
    private static CountDownLatch countDownLatch;

    public void oneWait() {
//        定义一组操作
        countDownLatch = new CountDownLatch(LATCH_SIZE);

//        定义5个线程去执行这组操作
        for (int i = 0; i < 5; i++) {
            new WorkThread().start();
        }

        System.out.println(Thread.currentThread().getName() + "等待其他线程完成一组操作");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "等待结束");
    }

    public void twoWait() {
//        定义一组操作
        countDownLatch = new CountDownLatch(LATCH_SIZE);

//        定义5个线程去执行这组操作
        for (int i = 0; i < 5; i++) {
            new WorkThread().start();
        }

        for (int i = 0; i < 2; i++) {
            new WaitThread().start();
        }
    }

    public static void main(String[] args) {
        TestCountDownLatch test=new TestCountDownLatch();
//        test.oneWait();
        test.twoWait();
    }

    static class WaitThread extends Thread{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "等待其他线程完成一组操作");
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "等待结束");
        }
    }

    static class WorkThread extends Thread{
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "执行操作。。。");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "执行操作结束。。。");
            countDownLatch.countDown();
        }
    }
}
